import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { isEmpty } from '@/utils/common'

function checkStatus(response: AxiosResponse) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error: any = new Error(response.statusText);
  error.response = response;
  throw error;
}

export const request = (url: string, options?: AxiosRequestConfig) => {
  // console.log(1)
  let userInfo: any = localStorage.getItem('userInfo');
  if (isEmpty(userInfo)) {
    // 如果用户信息为空
    userInfo = '{}'
  }
  const { token, userId } = JSON.parse(userInfo);

  let axiosConfig: AxiosRequestConfig = {
    url,
    method: 'GET',
    timeout: 20000,
    headers: {
      'Content-Type': 'application/json',
      'TL-System': 'umepos',
      'TL-Origin': 'umePass',
      'Accept-Language': 'zh-TW',
      'Request-Tk': token,
      'merId': '',
      'braId': localStorage.getItem('braId') || undefined,
      'umePassUserId': userId,
    },
    ...options,
  };

  /* 发起请求 */
  return axios(axiosConfig).then(checkStatus).then(res => {
    // console.log(res)
    return res.data
  }).catch(err => {
    console.log(err)
  })

}